package com.fw.utils;

import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


public class WechatUtil {

    private static final Logger logger = LoggerFactory.getLogger( WechatUtil.class);


    private static final String  APPID  =  "wx8f8df1519b76e918";//todo  注意替换
    private static final String  SECRET  =  "5a7e1c94012790d8425fe65c922e54c8";//todo  注意替换

    /**
     * 获取accessToken
     * @param code
     * @return
     * @throws IOException
     */
    public static WechatConfig getAccessToken(String code) {
        //获取access_token
        String  url  =  "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url = url.replace("APPID",  APPID);
        url = url.replace("SECRET",  SECRET);
        url = url.replace("CODE",  code);
        Connection.Response  response  = null;
        try {
            response = HttpUtils.get(url);
        } catch (IOException e) {
            logger.error("【微信授权】获取AccessToken失败：{}",e.getMessage());
            e.printStackTrace();
        }
        logger.info(response.body());
           WechatConfig wechatConfig = JSONObject.parseObject(response.body(),    WechatConfig.class);
        return wechatConfig;
    }

    /**
     * 获取用户信息
     * @param wechatConfig
     * @return
     * @throws IOException
     */
    public static WechatUserInfo getUserInfo( WechatConfig wechatConfig) {
        String  userinfoUrl  =  "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        userinfoUrl = userinfoUrl.replace("OPENID",  wechatConfig.getOpenid());
        userinfoUrl = userinfoUrl.replace("ACCESS_TOKEN",  wechatConfig.getAccess_token());
        Connection.Response  responseUserInfo  = null;
        try {
            responseUserInfo = HttpUtils.get(userinfoUrl);
        } catch (IOException e) {
            logger.error("【微信授权】:获取个人信息失败，原因：{}",e.getMessage());
            e.printStackTrace();
        }
/*
        System.out.print(responseUserInfo.body());
*/
        WechatUserInfo wechatUserInfo = JSONObject.parseObject(responseUserInfo.body(), WechatUserInfo.class);
        return wechatUserInfo;
    }




}
